package br.com.igrejacristavida.activity;

import java.util.concurrent.TimeUnit;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import br.com.igrejacristavida.model.Pregacao;

public class PregacaoPlayerActivity extends Activity {

	private static MediaPlayer player;
	private static String arquivoAtual;

	public TextView textPlayerTempoAtual, textPlayerTempoTotal;
	private int startTime = 0;
	private int finalTime = 0;
	private Handler myHandler = new Handler();
	private int forwardTime = 5000;
	private int backwardTime = 5000;
	private SeekBar seekPlayerPregacao;
	private ImageButton buttonPlay, buttonPause;
	public static int oneTimeOnly = 0;

	private Pregacao pregacao;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pregacao_player);
		setVolumeControlStream(AudioManager.STREAM_MUSIC);

		getActionBar().setDisplayHomeAsUpEnabled(true);

		pregacao = (Pregacao) getIntent().getExtras().getParcelable("pregacao");

		textPlayerTempoAtual = (TextView) findViewById(R.id.textPlayerTempoAtual);
		textPlayerTempoTotal = (TextView) findViewById(R.id.textPlayerTempoTotal);
		buttonPlay = (ImageButton) findViewById(R.id.buttonPlayerExecutar);

		seekPlayerPregacao = (SeekBar) findViewById(R.id.seekPlayerPregacao);
		seekPlayerPregacao.setClickable(false);

		buttonPause = (ImageButton) findViewById(R.id.buttonPlayerPausar);

		if (player != null && arquivoAtual != null && !arquivoAtual.equals(pregacao.getAudioUrl())) {
			player.stop();
			player = null;
		}

		myHandler.postDelayed(UpdateSongTime, 0);
	}

	public void play(View view) {
		Toast.makeText(getApplicationContext(), "Playing sound", Toast.LENGTH_SHORT).show();
		getMediaPlayer().start();

		if (oneTimeOnly == 0) {
			seekPlayerPregacao.setMax((int) finalTime);
			oneTimeOnly = 1;
		}
	}

	public void pause(View view) {
		Toast.makeText(getApplicationContext(), "Pausing sound", Toast.LENGTH_SHORT).show();

		getMediaPlayer().pause();
		buttonPause.setEnabled(false);
		buttonPlay.setEnabled(true);
	}

	public void forward(View view) {
		int temp = (int) startTime;
		if ((temp + forwardTime) <= finalTime) {
			startTime = startTime + forwardTime;
			getMediaPlayer().seekTo((int) startTime);
		} else {
			Toast.makeText(getApplicationContext(), "Cannot jump forward 5 seconds", Toast.LENGTH_SHORT).show();
		}
	}

	public void rewind(View view) {
		int temp = (int) startTime;
		if ((temp - backwardTime) > 0) {
			startTime = startTime - backwardTime;
			getMediaPlayer().seekTo((int) startTime);
		} else {
			Toast.makeText(getApplicationContext(), "Cannot jump backward 5 seconds", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.pregacao_player, menu);
		return true;
	}

	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);

		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			setContentView(R.layout.activity_pregacao_player_landscape);
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			setContentView(R.layout.activity_pregacao_player);
		}
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		Intent myIntent = new Intent(getApplicationContext(), PregacoesActivity.class);
		startActivityForResult(myIntent, 0);
		return true;
	}

	private MediaPlayer getMediaPlayer() {
		if (player == null) {
			try {
				progressDialog = ProgressDialog.show(this, "Aguarde", "Carregando a pregação...", true);
				arquivoAtual = pregacao.getAudioUrl();
				player = MediaPlayer.create(this, new Uri.Builder().encodedPath(arquivoAtual).build());
			} finally {
				progressDialog.dismiss();
			}
		}

		return player;
	}

	private Runnable UpdateSongTime = new Runnable() {
		public void run() {
			atualizarView();
			myHandler.postDelayed(this, 1000);
		}
	};

	private void atualizarView() {
		atualizarDadosDaPregacao();
		atualizarProgressoDoPlayer();
		atualizarBotoes();
	}

	private void atualizarDadosDaPregacao() {
		TextView nomePregacao = (TextView) findViewById(R.id.textPlayerNomePregacao);
		nomePregacao.setText(pregacao.getNome());

		TextView nomePregador = (TextView) findViewById(R.id.textPlayerNomePregador);
		nomePregador.setText(pregacao.getPregador());
	}

	private void atualizarBotoes() {
		if (player == null || !player.isPlaying()) {
			buttonPause.setEnabled(false);
			buttonPlay.setEnabled(true);
		} else if (player.isPlaying()) {
			buttonPause.setEnabled(true);
			buttonPlay.setEnabled(false);
		}
	}

	private void atualizarProgressoDoPlayer() {
		finalTime = getMediaPlayer().getDuration();
		startTime = getMediaPlayer().getCurrentPosition();

		textPlayerTempoTotal.setText(String.format(
				"%2d:%2d",
				TimeUnit.MILLISECONDS.toMinutes(finalTime),
				TimeUnit.MILLISECONDS.toSeconds(finalTime)
						- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(finalTime))));
		
		textPlayerTempoAtual.setText(String.format(
				"%2d:%2d",
				TimeUnit.MILLISECONDS.toMinutes(startTime),
				TimeUnit.MILLISECONDS.toSeconds(startTime)
						- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(startTime))));

		seekPlayerPregacao.setProgress(startTime);
	}
}
